package com.bqy.myokgo.base.okgo.callback;

import android.app.Activity;

import com.bqy.myokgo.base.manager.DialogManager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.request.base.Request;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Random;

import okhttp3.Response;

public abstract class isDialogCallback<T> extends Callback<T> {
    private Type type;
    private Class<T> clazz;
    private Activity context;
    private String TAG = "";
    /**
     * 控制是否显示Dialog
     */
    private boolean isDialog;

    public isDialogCallback(Activity activity, boolean isDialog) {
        super();
        this.context = activity;
        this.isDialog = isDialog;
    }

    /**
     * 网络请求开始
     */
    @Override
    public void onStart(Request<T, ? extends Request> request) {
        super.onStart(request);
        Random rand = new Random();
        int i = rand.nextInt(100000);
        TAG = context + " " + request.getUrl() + i;

        request.tag(TAG);
        DialogManager.getInstance().addHttpIS(TAG, isDialog, context);
    }

    /**
     * 失败
     */
    @Override
    public void onError(com.lzy.okgo.model.Response<T> response) {
        super.onError(response);
        for (int i = 0; i < DialogManager.listHttp.size(); i++) {
            OkGo.getInstance().cancelTag(DialogManager.listHttp.get(i));
        }
        DialogManager.getInstance().RemoveHttpAll();
    }

    /**
     * 成功
     * 该方法是子线程处理，不能做ui相关的工作
     * 主要作用是解析网络返回的 response 对象,生产onSuccess回调中需要的数据对象
     * 这里的解析工作不同的业务逻辑基本都不一样,所以需要自己实现,以下给出的时模板代码,实际使用根据需要修改
     */
    @Override
    public T convertResponse(Response response) throws Throwable {
        DialogManager.getInstance().RemoveHttp(TAG);
        OkGo.getInstance().cancelTag(TAG);
        if (type == null) {
            if (clazz == null) {
                Type genType = getClass().getGenericSuperclass();
                type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            } else {
                JsonConvert<T> convert = new JsonConvert<>(clazz);
                return convert.convertResponse(response);
            }
        }

        JsonConvert<T> convert = new JsonConvert<>(type);
        return convert.convertResponse(response);
    }

}